package Cn.Sarkar;


import Cn.Sarkar.IMS.useIMSModule
import Cn.Sarkar.MMS.LayerOne.registerMMSInterfaceInstances
import Cn.Sarkar.MMS.createServer
import Cn.Sarkar.MMS.useMMSModule
import Cn.Sarkar.PermissionManager.PermissionManager
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import io.ktor.application.install
import io.ktor.auth.Authentication
import io.ktor.auth.digest
import io.ktor.content.files
import io.ktor.content.static
import io.ktor.features.*
import io.ktor.gson.GsonConverter
import io.ktor.gson.gson
import io.ktor.http.ContentType
import io.ktor.http.HttpMethod
import io.ktor.locations.Locations
import io.ktor.response.respondRedirect
import io.ktor.routing.get
import io.ktor.routing.routing
import kotlinx.coroutines.experimental.runBlocking
import org.joda.time.DateTime
import org.slf4j.LoggerFactory

/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 11/5/17
Time: 10:25 AM
 */
val logger = LoggerFactory.getLogger("SarkarMMS")

fun main(args: Array<String>) = runBlocking {

    //    logger.info("Checking data base connection...")
//    IDataSource.openAndAutoClose {
//
//    }
//
//    logger.info("Data base configuration okay.")

    val server = createServer {

        install(Compression)
        install(CORS) {
            anyHost()
            method(HttpMethod.Get)
            method(HttpMethod.Post)
            method(HttpMethod.Put)
            method(HttpMethod.Delete)
        }
//        install(DefaultHeaders)
//        {
//            header("Access-Control-Allow-Origin", "*")
//            header("Developed-by", "Sarkar-Software-Technologys")
//        }
        install(CallLogging)
        install(ContentNegotiation) {
//
//            this.register(ContentType.Application.Json, KlaxonConverter()) {
//                klaxon.converter(object : Converter {
//                    val pattern = "yyyy-MM-dd HH:mm:ss"
//
//                    override fun canConvert(cls: Class<*>): Boolean = cls == DateTime::class.java
//
//                    override fun fromJson(jv: JsonValue): Any {
//                        return DateTime(java.text.SimpleDateFormat(pattern).parse(jv.string).time)
//                    }
//
//                    override fun toJson(value: Any): String = "\"${(value as DateTime).toString(pattern)}\""
//
//                })
//            }


            this.register(ContentType.Application.Json, GsonConverter()) {
                gson {
                    serializeNulls()


                    registerMMSInterfaceInstances()
                }
            }

        }

        install(Locations)
        install(PermissionManager) {

        }
        install(Authentication) {
            digest {
                realm = "yeganaaa"
                this.userNameRealmPasswordDigestProvider = { name, realm ->
                    val userName = "yeganaaa"
                    val pwd = 653125
                    digester.reset()
                    digester.update("${userName}:$realm:${pwd}".toByteArray())
                    digester.digest()
                }
            }
        }

        routing {

            useMMSModule()
            useIMSModule()

            static {
                files("Resources")
            }

            get("/") {
                context.respondRedirect("/MMS/index.html")
            }

        }
    }

    server.start()

    println("Server started successfully, Sarkar software technologys")

    Unit
}
